package base.thread_example.example01;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TicketSell {

    public static void main(String[] args) {
        TicketSell ts = new TicketSell();
        // 创建资源对象
        Ticket ticket = ts.new Ticket(10000);
        // 创建任务协议对象
        TicketRunnable runnable = ts.new TicketRunnable(ticket);

        // 创建4个卖票窗口
        new Thread( runnable,"t1").start();
        new Thread( runnable,"t2").start();
        new Thread( runnable,"t3").start();
        new Thread( runnable,"t4").start();
    }



    class TicketRunnable implements Runnable{
        private final Logger log = LoggerFactory.getLogger(TicketRunnable.class);
        private Ticket ticket;
        public TicketRunnable(Ticket ticket){
            this.ticket = ticket;
        }

        @Override
//        public synchronized void run() {// 可不能把 synchronized 放在run()方法上,否则就是单线程效果了
        // 如果synchronized是方法内部第一条语句,那么可以将synchronized定义在方法上.
        public void run() {
            while (true){
                synchronized (ticket){
                    if(ticket.getNum()>0)
                        ticket.sell();
                    else
                        break;
                }
            }
        }
    }

    class Ticket {
        private final Logger log = LoggerFactory.getLogger(Ticket.class);
        private int num;// 票数
        public Ticket(int num){
            this.num = num;
        }

        public void sell(){
            if(this.num <= 0){
                return;
            }
            log.info("{} 正在出售第 {} 张票", Thread.currentThread().getName(),this.num);
            num--;
        }

        public int getNum() {
            return num;
        }
        public void setNum(int num) {
            this.num = num;
        }
    }
}
